<?php
namespace app\admin\controller;
use app\admin\controller\Common;
use app\admin\model\GoodsLogic;
class Goods extends Common
{
	/**
     * 商品分类列表
     * FunctionName: categoryList
     * @author : roc
     */
    public function categoryList(){
        $GoodsLogic = new GoodsLogic;
        $cat_list = $GoodsLogic->goods_cat_list();
        $this->assign('cat_list',$cat_list);
        return view();
    }

    /**
     * 添加修改商品分类
     * FunctionName: addEditCategory
     * @author : roc
     */
    public function addEditCategory(){

        $GoodsLogic = new GoodsLogic;

        // $GoodsCategory = D('GoodsCategory'); //

        $type = input('post.id') > 0 ? 2 : 1; // 标识自动验证时的 场景 1 表示插入 2 表示更新
        //ajax提交验证
        if(request()->isAjax())
        {
            $data = input('post.');
            $parent_id = $data['parent_id_1'];
            $_POST['parent_id_2'] && ($parent_id = $_POST['parent_id_2']);
            $id = $data['id'];
            if($id > 0 && $parent_id == $id)
            {
                //  编辑
                $return_arr = array(
                    'status' => -1,
                    'message'   => '上级分类不能为自己',
                    'data'  => '',
                );
                echo json_encode($return_arr);exit;
            }
            unset($data['parent_id_1']);
            unset($data['id']);
            if ($type == 2)
            {
                db('goods_category')->where('id='.$id)->update($data);
                $GoodsLogic->refresh_cat($id);
            }
            else
            {
                $insert_id = db('goods_category')->insertGetId($data);
                $GoodsLogic->refresh_cat($insert_id);
            }
            $return_arr = array(
                'status' => 1,
                'message'   => '操作成功',
                'data'  => array('url'=>url('Goods/categoryList')),
            );
            echo json_encode($return_arr);exit;
        }

        if(request()->isGet())
        {
            $id = input('route.id')?input('route.id'):0;
            // dump($id);exit;
            $goods_category_info = db('goods_category')->where('id='.$id)->find();
            $level_cat = $GoodsLogic->find_parent_cat($goods_category_info['id']); // 获取分类默认选中的下拉框

            $cate = db('goods_category')->select(); // 已经改成联动菜单
            $cat_list = unlimitedForLevel($cate,'',0);

            //模板
            $template = db('template')->where('is_hide=0')->order('sort asc')->select();
            $this->assign('template_lists',$template);//模板

            //关联属性组
            $attribute_kinds = db('attribute_kind')->select();
            $this->assign('attribute_kinds',$attribute_kinds);

            $this->assign('level_cat',$level_cat);
            $this->assign('cat_list',$cat_list);
            $this->assign('goods_category_info',$goods_category_info);
            return view('_category');
            exit;
        }

    }

    /**
     * 删除商品分类
     * FunctionName: delGoodsCategory
     * @author : roc
     */
    public function delGoodsCategory(){
        // 判断子分类
        $id = input('route.id');
        $count = db('goods_category')->where("parent_id = {$id}")->count("id");
        $count > 0 && $this->error('该分类下还有分类不能删除!',url('Goods/categoryList'));
        // 判断是否存在商品
        $goods_count = db('Goods')->where("cat_id = {$id}")->count('1');
        $goods_count > 0 && $this->error('该分类下有商品不能删除!',url('Goods/categoryList'));
        // 删除分类
        db('goods_category')->where("id = {$id}")->delete();
        $this->success("操作成功!!!",url('Goods/categoryList'));
    }

    /**
     * 商品列表
     * FunctionName: goodsList
     * @author : roc
     */
    public function goodsList(){
        $GoodsLogic = new GoodsLogic;
        // $brandList = $GoodsLogic->getSortBrands();
        $categoryList = $GoodsLogic->getSortCategory();
        $this->assign('categoryList',$categoryList);
        $this->assign('brandList',$brandList);

        $sel_id = input('get.sel_id');
        //商品栏目
        $article_kind = db('goods_category')->select();
        // $article_kinds = unlimitedNavLevel($article_kind);
        $this->assign('article_kinds',$article_kind);

        $list = array();
        $size = empty($_REQUEST['size']) ? 25 : $_REQUEST['size'];
        $where['is_del'] = 0;
        if($sel_id){
            $where['cat_id'] = $sel_id;
        }

        $count = db('goods')->where($where)->count();// 查询满足要求的总记录数

        $list = db('goods')->where($where)->order('goods_id desc')->paginate($size,$count)->each(function($item,$key){
            return $item;
        });
        $page = $list->render();

        $handle_add = url('Goods/addEditGoods',array('act'=>'add','sel_id'=>$sel_id));
        $this->assign('handle_add',$handle_add);
        $this->assign('goodsList',$list); // 商品数据
        $this->assign('page',$page);// 赋值分页输出
        $this->assign('total',$count);
        $this->assign('sel_id',$sel_id);
        // print_r($list);exit;
        return view();

        // $Goods =  M('Goods');
        // $size = empty($_REQUEST['size']) ? 25 : $_REQUEST['size'];
        // $where['is_del'] = 0;
        // if($sel_id){
        //     $where['cat_id'] = $sel_id;
        // }
        // $count = $Goods->where($where)->count();// 查询满足要求的总记录数
        // $pager = new \Think\Page($count,$size);// 实例化分页类 传入总记录数和每页显示的记录数
        // $res = $Goods->where($where)->order('goods_id desc')->limit($pager->firstRow.','.$pager->listRows)->select();
        // $page = $pager->show();//分页显示输出

        // if($res){
        //     foreach ($res as $val){
        //         foreach ($article_kind as $value) {
        //             if($val['cat_id'] == $value['id']){
        //                 $val['category'] = $value['name'];
        //             }
        //         }
        //         $val['handle_url'] = U('Goods/addEditGoods',array('act'=>'edit','goods_id'=>$val['goods_id'],'sel_id'=>$sel_id));
        //         $list[] = $val;
        //     }
        // }
        // $handle_add = U('Goods/addEditGoods',array('act'=>'add','sel_id'=>$sel_id));
        // $this->assign('handle_add',$handle_add);
        // $this->assign('goodsList',$list); // 商品数据
        // $this->assign('page',$page);// 赋值分页输出
        // $this->assign('total',$count);
        // $this->assign('sel_id',$sel_id);

        // $this->display();
    }

    /**
     * 添加修改商品
     * FunctionName: addEditGoods
     * @author : roc
     */
    public function addEditGoods(){

        $GoodsLogic = new GoodsLogic;
        // $Goods = D('Goods'); //
        // $type = $_POST['goods_id'] > 0 ? 2 : 1; // 标识自动验证时的 场景 1 表示插入 2 表示更新
        $goods_id = input('route.goods_id')?input('route.goods_id'):0;
        $act = input('route.act');
        $sel_id = input('route.sel_id');
        
        $goodsInfo = db('goods')->where('goods_id='.$goods_id)->find();
        // dump($goodsInfo['goods_norms']);
        $goodsInfo['handle_url'] = url('Goods/GoodsHandle',array('sel_id'=>$sel_id));

        $thumb_list = json_decode($goodsInfo['thumb_list']);//图片列表--新

        $level_cat = $GoodsLogic->find_parent_cat($goodsInfo['cat_id']); // 获取分类默认选中的下拉框

        $article_kind = db('goods_category')->select();// 已经改成联动菜单
        // $article_kinds = unlimitedNavLevel($article_kind); 
        // $cat_list = unlimitedForLevel($article_kinds,'',0);

        // $brandList = $GoodsLogic->getSortBrands();
        // $goodsType = M("GoodsType")->select();

        $goodsInfo['start_time'] = date('Y-m-d',$goodsInfo['start_time']);
        $goodsInfo['end_time'] = date('Y-m-d',$goodsInfo['end_time']);
        $goodsInfo['pics_arr'] = json_decode($goodsInfo['thumb_list']);
        $this->assign('min_date',date('Y-m-d'));
        $this->assign('level_cat',$level_cat);
        $this->assign('cat_list',$article_kind);
        $this->assign('brandList',$brandList);
        $this->assign('goodsType',$goodsType);
        $this->assign('act',$act);
        $this->assign('sel_id',$sel_id);
        $this->assign('goodsInfo',$goodsInfo);  // 商品详情
        // $goodsImages = M("GoodsImages")->where('goods_id ='.I('GET.id',0))->select();
        $this->assign('goodsImages',$goodsImages);  // 商品相册
        $this->assign('thumb_list',$thumb_list);

        // attr属性
        // $goods_attributes = M('Goods_attr')->where(array('goods_id'=>$goods_id))->select();
        // // dump($goods_attributes);

        // $attributes = M('Attribute_type')->select();
        // foreach ($attributes as $key => $value) {
        //     # code...
        //     $attributes[$key]['sub_attrs'] = M('Attribute')->where(array('tid'=>$value['id']))->select();
        // }
        // $norms = M('Goods_norm')->where(array('goods_id'=>$goods_id))->select();

        // $this->assign(array(
        //     'attributes'=>$attributes,
        //     'goods_attributes'=>$goods_attributes,
        //     'norms'=>$norms,//规格
        //     ));

        return view('_goods');
    }


    public function GoodsHandle(){
        $GoodsLogic = new GoodsLogic;
        // $Goods = D('Goods'); //
        // $type = $_POST['goods_id'] > 0 ? 2 : 1; // 标识自动验证时的 场景 1 表示插入 2 表示更新
        $data = input('post.');
        $data['thumb_list'] = !empty($data['thumb_list']) ? json_encode($data['thumb_list']) : '' ;
        //ajax提交验证
        if(request()->isAjax()){
            $data['start_time'] = strtotime($data['start_time']);
            $data['end_time'] = strtotime($data['end_time']);
            $data['shop_price'] = $data['shop_price'] ? $data['shop_price'] : 0;
            $data['market_price'] = $data['market_price'] ? $data['market_price'] : 0;

            /*$_POST['cat_id_2'] && ($Goods->cat_id = $_POST['cat_id_2']);
            $_POST['cat_id_3'] && ($Goods->cat_id = $_POST['cat_id_3']);*/
            $data['is_hot'] = $data['is_hot'] ? $data['is_hot'] : 0;
            $data['is_hide'] = $data['is_hide'] ? $data['is_hide'] : 0;
            $data['down_color'] = $data['down_color'] ? $data['down_color'] : 0;
            $data['down_soft'] = $data['down_soft'] ? $data['down_soft'] : 0;
            $data['short_content'] = htmlspecialchars_decode($data['short_content']);
            $data['goods_content'] = htmlspecialchars_decode($data['goods_content']);
            $data['goods_norms'] = htmlspecialchars_decode($data['goods_norms']);
            $data['goods_remark'] = htmlspecialchars_decode($data['goods_remark']);
            $data['goods_service'] = htmlspecialchars_decode($data['goods_service']);

            //多图
            if(!empty($data['slide_img'])){
                $s_img = $data['slide_img'];
                $s_alt = $data['slide_alt'];
                $s_order = $data['slide_order'];
                for($i=0;$i<count($s_img);$i++){
                    $s_order[$i] = empty($s_order[$i])?50:$s_order[$i];
                    $pics[] = array(
                        'image'=>$s_img[$i],
                        'alt'=>$s_alt[$i],
                        'order'=>$s_order[$i],
                    );
                }
                // dump($pics);
                //排序开始，数组中根据某个元素排序
                $sort = array(
                 'direction' => 'SORT_ASC', //排序顺序标志 SORT_DESC 降序；SORT_ASC 升序
                 'field'     => 'order',       //排序字段
                );
                $arrSort = array();
                foreach($pics AS $uniqid => $row){
                    foreach($row AS $key=>$value){
                        $arrSort[$key][$uniqid] = $value;
                    }
                }
                if($sort['direction']){
                    array_multisort($arrSort[$sort['field']], constant($sort['direction']), $pics);
                }
                //排序结束
                // dump($pics);exit;
                $data['thumb_list'] = json_encode($pics);
            }else{
                $data['thumb_list'] = '';
            }
            unset($data['slide_img']);
            unset($data['slide_alt']);
            unset($data['slide_order']);
            // dump($data['attribute']);
            // dump($data);exit;
            // exit;
            if($data['act'] == 'add'){
                unset($data['act']);
                unset($data['sel_id']);
                unset($data['attribute']);
                unset($data['guige']);
                unset($data['down_color']);
                unset($data['down_soft']);
                $data['on_time'] = time(); // 上架时间----只有增加的时候才写入
                $r = db('goods')->insertGetId($data); // 写入数据到数据库
                //attr
                // if($data['attribute']){
                //     foreach ($data['attribute'] as $attribute) {
                //         db('goods_attr')->add(array('goods_id'=>$r,'attr_id'=>$attribute));
                //     }
                // }
                if($r){
                    $json = array('status' => 1,'message' => '添加成功' ,'url' => url('Goods/goodsList',array('sel_id'=>input('post.sel_id'))) );
                    echo json_encode($json);exit;
                }
                // $Goods->afterSave($goods_id);                    
            }
            if($data['act'] == 'edit'){
                unset($data['act']);
                unset($data['sel_id']);
                unset($data['attribute']);
                unset($data['guige']);
                unset($data['down_color']);
                unset($data['down_soft']);
                $r = db('goods')->where(array('goods_id'=>$data['goods_id']))->update($data); // 写入数据到数据库
                //attr
                // if($data['attribute']){
                //         M('Goods_attr')->where(array('goods_id'=>$data['goods_id']))->delete();
                //     foreach ($data['attribute'] as $attribute) {
                //         M('Goods_attr')->add(array('goods_id'=>$data['goods_id'],'attr_id'=>$attribute));
                //     }
                // }
                //规格
                if($r !== false){
                    $json = array('status' => 1,'message' => '修改成功','url' => url('Goods/goodsList',array('sel_id'=>input('post.sel_id'))) );
                    echo json_encode($json);exit;
                }
            }
            $json = array('status' => 0,'message' => '操作失败' );
            echo json_encode($json);exit;

        }
    }















}